package com.link.base.base.consumer.controller;

import com.alibaba.fastjson.JSON;
import com.link.base.base.consumer.model.QidianAccntWeixin;
import com.link.base.user.model.CoreUser;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.consumer.service.WxConsumerService;
import com.link.core.cllog.LCLogger;
import com.link.base.wechat.wxplatform.model.WxPlatform;
import com.link.base.wechat.wxsubscriber.model.Subscriber;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.ServiceException;
import com.link.core.modules.export.ExportFactory;
import com.link.core.modules.export.ExportWriter;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信消费者
 * @author Li Yang
 */
@Controller
@RequestMapping("/link/wxConsumer")
public class WxConsumerController extends BasicController<Subscriber> {

    @Resource
    private WxConsumerService wxConsumerService;

    @Resource
    private AccountService accountService;

    /**
     * 查询消费者页面
     * @author Li Yang
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/queryWxConsumerPage")
    @ResponseBody
    public Map<String, Object> queryWxConsumerPage(@JsonParam QueryParams qps, HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        List<Account> list = new ArrayList<Account>();
        try {

            Account t = (Account) BasicModel.transformClass(Account.class, qps);
            t.setAcctType("ChannelConsumer");
            //t.setAcctChannelType("OfficialAccount");
            list = accountService.queryByExamplePage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Account>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 导出消费者
     * @author Li Yang
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/queryWxConsumerPage/exportData")
    @ResponseBody
    public Map<String, Object> exportQueryWxConsumerPage(@JsonParam QueryParams qps, HttpSession session,
                                                         HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        List<Account> list = new ArrayList<Account>();
        try {
            CoreUser user = UserUtil.getUser();
            ExportWriter exportWriter;
            String exportType = "xlsx";
            String exportFileType = qps.getExportFileType();
            if (exportType.equals(exportFileType)) {
                exportWriter = ExportFactory.newExcelInstance(qps);
            } else {
                exportWriter = ExportFactory.newInstance(qps);
            }
            Account t = (Account) BasicModel.transformClass(Account.class, qps);
            t.setAcctType("ChannelConsumer");
            //t.setAcctChannelType("OfficialAccount");
            t.setPageFlag(false);
            list = accountService.queryByExamplePage(t);
            exportWriter.wirteData(list);
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 微信公众号解除绑定
     * @author Li Yang
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/unbindWxPlatform")
    @ResponseBody
    public Map<String, Object> unbindWxPlatform(@JsonParam WxPlatform entity, HttpSession session,
                                                       HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (null == entity.getId()) {
                throw new ServiceException("PUBLIC-007");
            }
            wxConsumerService.unbindWxPlatform(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 更新是否开启同步粉丝功能
     * @author Li Yang
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/wxAutoTransStatusUpdate")
    @ResponseBody
    public Map<String, Object> wxAutoTransStatusUpdate(@JsonParam WxPlatform entity, HttpSession session,
                                                       HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(2);
        try {
            if (null == entity.getId()) {
                throw new ServiceException("PUBLIC-007");
            }
            wxConsumerService.wxAutoTransStatusUpdate(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 根据weixin_og_id查询其所属帐套，提供成接口给微信工程调用
     *
     * @author 黄龙建
     * @date 2020年06月10日
     * @param entity 对象
     */
    @RequestMapping(value = "/queryCorpByWxAppOrOgId")
    @ResponseBody
    public Map<String, Object> queryCorpByWxAppOrOgId(@RequestBody WxPlatform entity, HttpSession session,
                                                       HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            WxPlatform wxPlatform = wxConsumerService.queryCorpByWxAppOrOgId(entity);
            result.put("success", true);
            result.put("result", wxPlatform);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * 获取微信订阅者信息，提供成接口给微信工程调用
     *
     * @param reqMap 对象
     * @author 黄龙建
     * @date 2020年06月10日
     */
    @RequestMapping(value = "/wxInsertOrUpdateSub")
    @ResponseBody
    public Map<String, Object> wxInsertOrUpdateSub(@RequestBody Map<String, String> reqMap, HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            String authorizerAppid = reqMap.get("authorizerAppid");
            String custermname = reqMap.get("custermname");
            String wxPlatformString = reqMap.get("wxPlatform");
            WxPlatform wxPlatform = JSON.parseObject(wxPlatformString, WxPlatform.class);
            Subscriber subscriber = wxConsumerService.getSubscriberInfo(authorizerAppid, custermname, wxPlatform);
            int insertResult = wxConsumerService.insertOrUpdateSub(subscriber);
            result.put("success", true);
            result.put("result", insertResult);
            result.put("result2", subscriber);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 将微信粉丝转换为消费者，提供成接口给微信工程调用
     *
     * @author 黄龙建
     * @date 2020年06月11日
     */
    @RequestMapping(value = "/generateWxSub2Consumer")
    @ResponseBody
    public Map<String, Object> generateWxSub2Consumer(@RequestBody Map<String, String> reqMap, HttpSession session,
                                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            String subStr = reqMap.get("sub");
            String subListStr = reqMap.get("subList");
            String corpAdminIdStr = reqMap.get("corpAdminId");
            List<Account> accountList = wxConsumerService.generateWxSub2Consumer(JSON.parseObject(subStr, Subscriber.class),
                    JSON.parseArray(subListStr, Subscriber.class), Long.parseLong(corpAdminIdStr));
            result.put("success", true);
            result.put("result", accountList);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 取消（修改）粉丝列表粉丝的关注状态，提供成接口给微信工程调用
     *
     * @author 黄龙建
     * @date 2020年06月11日
     */
    @RequestMapping(value = "/wxUpdateUnsubscribe")
    @ResponseBody
    public Map<String, Object> wxUpdateUnsubscribe(@RequestBody Subscriber sub, HttpSession session,
                                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            wxConsumerService.wxUpdateUnsubscribe(sub);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 根据客户openId及corpId查询客户信息，提供成接口给微信工程调用
     *
     * @author 黄龙建
     * @date 2020年06月11日
     */
    @RequestMapping(value = "/queryAccountByOpenId")
    @ResponseBody
    public Map<String, Object> queryAccountByOpenId(@RequestBody Account account, HttpSession session,
                                                    HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            Account accountRet = wxConsumerService.queryAccountByOpenId(account);
            result.put("success", true);
            result.put("result", accountRet);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 给微信/客户中间表插入记录，提供成接口给微信工程调用
     *
     * @author 黄龙建
     * @date 2020年06月11日
     */
    @RequestMapping(value = "/insertOrUpdateAccountWeixin")
    @ResponseBody
    public Map<String, Object> insertOrUpdateAccountWeixin(@RequestBody QidianAccntWeixin QidianAccntWeixin,
                                                           HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            int retNum = wxConsumerService.insertOrUpdateAccountWeixin(QidianAccntWeixin);
            result.put("success", true);
            result.put("result", retNum);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 更新客户表ACCNT_2D_SEQ的值，提供成接口给微信工程调用
     *
     * @author 黄龙建
     * @date 2020年06月11日
     */
    @RequestMapping(value = "/updateWx2code")
    @ResponseBody
    public Map<String, Object> updateWx2code(@RequestBody Account account, HttpSession session,
                                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            wxConsumerService.updateWx2code(account);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * 将微信信息缓存在redis中，提供成接口给微信工程调用
     *
     * @author 黄龙建
     * @date 2020年06月11日
     */
    @RequestMapping(value = "/uploadWxOnRedis")
    @ResponseBody
    public Map<String, Object> uploadWxOnRedis(@RequestBody Subscriber sub, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            wxConsumerService.uploadWxOnRedis(sub);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
